package com.xsd.bio;


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: BIO 通信实例
 * @Author: zhoufuzong
 * @Created: 2021-01-19 21:43:50
 * @Version: 1.1.0
 */

public class BIOServer {
    public static void main(String[] args) throws IOException {
        // 线程池机制

        // 思路：
        // 1. 创建一个线程池
        // 2. 如果有客户端连接，就创建一个线程，与之通信（单独写一个方法）

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                0,
                Integer.MAX_VALUE,
                60L,
                TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(),
                new threadFactory1("BIOTest"),
                new ThreadPoolExecutor.AbortPolicy()
                );
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了");
        while (true) {
            System.out.println("线程信息 id："+Thread.currentThread().getId()+"\t 线程名："+Thread.currentThread().getName());
            System.out.println("wait.....");
            // 监听，等待客户端连接
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            // 创建一个线程，与之通信
            threadPoolExecutor.execute(() -> {
                // 可以和客户端通讯
                handler(socket);
            });
        }


    }

    // 编写一个handler方法，和客户端通讯
    public static void handler(Socket socket){

        try {
            System.out.println("线程信息 id："+Thread.currentThread().getId()+"\t 线程名："+Thread.currentThread().getName());
            System.out.println("read....");
            byte[] bytes =  new byte[1024];
            // 通过socket 获取输入流
            InputStream inputStream = socket.getInputStream();
            while (true) {
                int read = inputStream.read(bytes);
                if (read!=-1){
                    // 输出客户端发送的数据
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭client连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

class threadFactory1 implements ThreadFactory{
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    threadFactory1(String name) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" +
                 name+
                "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}

